<?php
namespace app\admin\controller;

use app\admin\model\AttachmentModel;
use think\Db;
class Attachment extends Base
{
	public function index(){
		if(request()->isAjax()){
			$param = input('param.');
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$Model = new AttachmentModel();
			$return['rows'] = $Model->getInfoByWhere('',true,$offset,$limit,'create_time desc');
			foreach ($return['rows'] as $k => $v){
				$v['size'] = round($v['size'] /1024 /1024,4);
				$v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
				$v['status'] == '1' ? $v['status_name'] = "启用" : $v['status_name'] = "禁用";
			}
			$return['total'] = count($Model->getInfoByWhere('',false));
			return ['code'=>1,'msg'=>'表格加载成功','data'=>$return];
		}
		return $this->fetch();
	}

	public function setAttachStatus(){
		$id = input('post.param/a');
		$attach = new AttachmentModel($id);
		$return = $attach->setstatus($id);
		return $return;
	}

	public function uploadAttach(){
		if (!isset($_FILES["file"])||empty($_FILES["file"])) {
            return json(['code'=>0,'msg'=>'没有上传文件']);
        } else {
            $name = $_FILES["file"]["name"];
            $ext = explode('.',$name);
            $ext = $ext[sizeof($ext)-1];
            $size = $_FILES["file"]["size"];
            $tmp = $_FILES["file"]["tmp_name"];
            $data_ext = config('ext');
			if(!in_array($ext, $data_ext)){
				return json(['code' => 0,'msg' => '文件格式错误']);
			}
            if (in_array($ext,config('ext'))){
                if ($size <= config('max_size_of_upload')){
                    $time = strtotime(date("Y-m-d"));
					if(input('targetpath') == ''){
						$path = "upload/attachments/".session('username').session('id')."/".date("Ymd");
					}else{
						$patharr = explode("/",input('targetpath'));
						unset($patharr[sizeof($patharr)-1]);
						$path = implode("/",$patharr);
						$path = "upload/".$path;
						$path = iconv("UTF-8", "GBK", $path);
					}
                    try {
                        if (!is_dir($path)) {
                            mkdir($path, 0777, true);
                        }
                        if(input('targetpath') == ''){
                        	$db_name = session('username') . session('id') ."_".date("His").rand(1000,9999);
							$save = $path."/".$db_name.'.'.$ext;
                        }else{
                        	$save = "upload/".input('targetpath').'.'.$ext;
                        	$db_name = explode('/',input('targetpath'));
                        	$db_name = $db_name[sizeof($db_name)-1];
                        	DB::name('attachment')->where('path',$save)->delete();
                        }

						$url = "/" . $save;
                        if (move_uploaded_file($tmp, iconv("UTF-8", "GBK", $save))) {
                            $id = DB::name('attachment')->insertGetId([
                            	"name"=>$db_name,
                            	"path"=>$save,
                            	"size"=>$size,
                            	"ext"=>$ext,
                            	"url"=>$url,
                            	"create_time"=>time(),
                            	'create_uid'=>session('id')
                            ]);
                            return json(['code'=>1,'msg'=>' 上传成功','data'=>['id'=>$id,'path'=>$url]]);
                        }
                    } catch (Expectation $e) {
                        return json(['code'=>0,'msg'=>'上传失败'.$e->getMessage()]);
                    }

                } else {
                    return json(['code'=>0,'msg'=>'上传文件过大']);
                }
            } else {
                return json(['code'=>0,'msg'=>"上传格式不被允许"]);
            }
        }
	}

	public function delAttach($param){
		$ids = $param;
		DB::startTrans();
		try{
			foreach($ids as $v){
				$path = DB::name('attachment')->where('id',$v)->value('path');
				DB::name('attachment')->where('id',$v)->delete();
				if(file_exists(APP_PATH."../public/".$path) && $path != ''){
					unlink(APP_PATH."../public/".$path);
				}
			}
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		}catch(Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
		}

	}
}
